from flask_admin import Admin
from flask_admin.contrib.sqla import ModelView
from flask_admin.contrib.sqla.filters import FilterEqual, FilterEmpty
from flask_sqlalchemy.model import DefaultMeta
from sqlalchemy import func
from sqlalchemy.inspection import inspect

admin = Admin(name='order_project', template_mode='bootstrap3')


class CModelView(ModelView):
    """
    继承ModelView的类，做一些基础配置
    """
    _column_labels = {}
    column_display_pk = True  # 显示主键
    can_set_page_size = True  # 可调整每页大小
    can_view_details = True  # 可查看详情
    edit_modal = True  # 以对话框形式创建
    create_modal = True  # 以对话框形式编辑
    column_exclude_list = ('create_time', 'update_time')  # 列表不显示
    form_widget_args = {  # 表单配置
        'create_time': {'readonly': True, 'disabled': True},
        'delete_time': {'readonly': True, 'disabled': True},
        'update_time': {'readonly': True, 'disabled': True},
    }

    column_searchable_list = ['id']  # 可搜索项
    page_size = 100

    column_formatters = {
        'delete_time': lambda v, c, m, p: "已删除" if m.delete_time else ""
    }

    column_filters = ['delete_time']


def init_models(_models):
    """
    初始化models，admin上显示所有表单，无需一个一个配置添加
    :param _models: models文件，如app中的models
    :return:
    """
    for i in dir(_models):
        # table = inspect(i)
        _model = getattr(_models, i)
        if not isinstance(_model, DefaultMeta) or i == 'CModel':
            continue

        # 获得models对象
        model_fields = inspect(_model)
        # 填充备注
        CModelView.column_labels = {column.name: column.comment for column in model_fields.columns}
        CModelView.column_labels['delete_time'] = '删除'

        # 表添加到admin
        admin.add_view(CModelView(_model, _models.db.session))
